package com.cn.ZhiKeDianShang.ui.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.cn.ZhiKeDianShang.AppConfig;
import com.cn.ZhiKeDianShang.R;
import com.cn.ZhiKeDianShang.adapter.DeclarationAdapter;
import com.cn.ZhiKeDianShang.base.BaseActivity;
import com.cn.ZhiKeDianShang.model.event.updateDeclarationBean;
import com.cn.ZhiKeDianShang.model.response.BlList;
import com.cn.ZhiKeDianShang.model.response.getTeamBean;
import com.cn.ZhiKeDianShang.presenter.MineFragmentPresenter;
import com.cn.ZhiKeDianShang.presenter.view.MineFragmentView;
import com.cn.ZhiKeDianShang.util.ProgressDialogFragment;
import com.cn.ZhiKeDianShang.util.ToastUtil;
import com.cn.ZhiKeDianShang.util.view.SelectionFrame;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.HttpUtils;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.result.ObjectResult;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.result.Result;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.Call;

/**
 * 报单列表
 * Created by chengaofu on 2017/6/21.
 */

public class ReclarationActivity extends BaseActivity<MineFragmentView, MineFragmentPresenter> implements MineFragmentView {


    @BindView(R.id.rc_list)
    RecyclerView mRecyclerView;
    @BindView(R.id.fragment_list_swip)
    SwipeRefreshLayout fragmentListSwip;
    @BindView(R.id.rl_image_text)
    RelativeLayout rlImageText;
    @BindView(R.id.ll_empty)
    RelativeLayout ll_empty;


    Unbinder unbinder;

    private ProgressDialogFragment mProgressDialog;

    int currentPage = 1;
    int pageNumber = 10;
    //上拉加载  还有没有数据
    boolean isHaveDate = true;

    private List<BlList.BdBean> mList = new ArrayList<>();


    private DeclarationAdapter mAdapter;

    @Override
    protected void initViewsAndEvents() {
        fragmentListSwip.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                currentPage = 1;
                getData();
            }
        });
        getData();
        initRecyclerView();
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {

            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                //得到当前显示的最后一个item的view
                View lastChildView = recyclerView.getLayoutManager().getChildAt(recyclerView.getLayoutManager().getChildCount() - 1);
                if (lastChildView != null) {
                    //得到lastChildView的bottom坐标值
                    int lastChildBottom = lastChildView.getBottom();
                    //得到Recyclerview的底部坐标减去底部padding值，也就是显示内容最底部的坐标
                    int recyclerBottom = recyclerView.getBottom() - recyclerView.getPaddingBottom();
                    //通过这个lastChildView得到这个view当前的position值
                    int lastPosition = recyclerView.getLayoutManager().getPosition(lastChildView);

                    //判断lastChildView的bottom值跟recyclerBottom是否相等
                    //判断lastPosition是不是最后一个position
                    if (lastChildBottom == recyclerBottom && lastPosition == recyclerView.getLayoutManager().getItemCount() - 1) {
                        ToastUtil.showShort("滑动到底部了");
                        if (isHaveDate) {
                            currentPage++;
                            getData();
                        }
                    }
                }
            }
        });

    }

    /**
     * 添加或是更改 成功刷新数据
     *
     * @param messageEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void XXX(updateDeclarationBean messageEvent) {
        Log.d("Debug", "收到eventbus 类型为" + messageEvent.getType());
        if (messageEvent.getType() == 1) {
            //添加操作
            currentPage = 1;
            getData();
        } else if (messageEvent.getType() == 2) {
            //修改操作
            BlList.BdBean bdBean = mList.get(messageEvent.getPosition());
            BlList.BdBean dateBean = messageEvent.getDateBean();
            bdBean.setAid(dateBean.getAid());
            bdBean.setNickname(dateBean.getNickname());
            bdBean.setNum(dateBean.getNum());
            bdBean.setRemark(dateBean.getRemark());
            mAdapter.notifyDataSetChanged();
        }

    }


    AlertDialog alertDialog = null;

    private void initRecyclerView() {
        mAdapter = new DeclarationAdapter(ReclarationActivity.this, R.layout.item_declaration_like, mList, new DeclarationAdapter.onItemClick() {
            @Override
            public void update(int position) {
                Intent intent = new Intent(ReclarationActivity.this, AddDeclarationActivity.class);
                intent.putExtra("isAdd", false);
                intent.putExtra("dateBean", mList.get(position));
                intent.putExtra("position", position);
                startActivity(intent);
            }

            @Override
            public void deal(int position) {
                //含有取消的弹窗
                SelectionFrame selectionFrame1 = new SelectionFrame(ReclarationActivity.this);
                selectionFrame1.setSomething(null, "是否删除当前报单", new SelectionFrame.OnSelectionFrameClickListener() {
                    @Override
                    public void cancelClick() {
                    }

                    @Override
                    public void confirmClick() {
                        //调用成功 弹窗消失  失败 弹窗不消失
                        Delete(mList.get(position).getId(),position);
                    }
                });
                selectionFrame1.show();
            }
        });

        mRecyclerView.setLayoutManager(new LinearLayoutManager(ReclarationActivity.this));
        mRecyclerView.setAdapter(mAdapter);
    }


    /**
     * 删除报单
     */
    private void Delete(String id,int postion) {
//        DialogHelper
        Map<String, String> params = new HashMap<>();
        params.put("id", id);
        HttpUtils.post().url( AppConfig.BD_DELETE)
                .params(params)
                .addSecret()
                .build()
                .execute(new BaseCallback<getTeamBean>(getTeamBean.class) {
                    @Override
                    public void onResponse(ObjectResult<getTeamBean> result) {
//                        DialogHelper.dismissProgressDialog();
                        if (Result.checkSuccess(ReclarationActivity.this, result)) {
                            mList.remove(postion);
                            mAdapter.notifyDataSetChanged();
                            ToastUtil.showShort(result.getResultMsg());
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
//                        DialogHelper.dismissProgressDialog();
//                        ToastUtil.showErrorNet(LoginActivity.this);
                    }
                });
    }



    /**
     * @param
     */
    private void getData() {
        Map<String, String> params = new HashMap<>();
        params.put("page", currentPage + "");
        params.put("pagesize", pageNumber + "");
        HttpUtils.post().url(AppConfig.BD_LISTS)
                .params(params)
                .addSecret()
                .build()
                .execute(new BaseCallback<BlList>(BlList.class) {
                    @Override
                    public void onResponse(ObjectResult<BlList> result) {
                        if (Result.checkSuccess(ReclarationActivity.this, result)) {
                            BlList data = result.getData();
                            if (currentPage == 1) {
                                mAdapter.setData(data.getBd());
                                if (data.getBd().size() == 0) {
                                    ll_empty.setVisibility(View.VISIBLE);
                                } else {
                                    ll_empty.setVisibility(View.GONE);
                                }
                            } else {
                                ll_empty.setVisibility(View.GONE);
                                mAdapter.addAll(data.getBd());
                            }
                            //所返回的数据个数 没有pageNumber 个的  说明已经没有数据了
                            if (data.getBd().size() != pageNumber) {
                                isHaveDate = false;
                            } else {
                                isHaveDate = true;
                            }
                            mList = mAdapter.getAll();
                            mAdapter.notifyDataSetChanged();
                        }
                        if (fragmentListSwip != null) {
                            fragmentListSwip.setRefreshing(false);
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        if (fragmentListSwip != null) {
                            fragmentListSwip.setRefreshing(false);
                        }
                    }
                });
    }


    @Override

    public void onResume() {
        super.onResume();

    }

    @Override
    protected int getErrorLayoutId() {
        return R.layout.declaration_layout;
    }

    @Override
    protected int getNormalLayoutId() {
        return R.layout.declaration_layout;
    }

    @Override
    protected MineFragmentPresenter createPresenter() {
        return null;
    }


    @Override
    public void requestFailed(String message) {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }


    @OnClick({R.id.setting_back, R.id.tv_add})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.setting_back:
                finish();
                break;
            case R.id.tv_add:

                Intent intent = new Intent(ReclarationActivity.this, AddDeclarationActivity.class);
                intent.putExtra("isAdd", true);
                startActivity(intent);
                break;

        }
    }

}